// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <pollux/expression/vector_function.h>

namespace kumo::pollux::functions::sparksql {
    class ArraySort : public exec::VectorFunction {
        /// This class implements generic array sort function. Takes an array as input
        /// and sorts it according to provided comparator |Cmp| as template parameter.
        /// Additionally |nullsFirst| ctor parameter can be used to configure nulls
        /// sort order. If |nullsFirst| is  true nulls are moved to front of array,
        ///  otherwise nulls are moved to end of array.
        ///
        /// Sorts floating points as per following ascending order:
        /// -Inf < Inf < NaN

    public:
        explicit ArraySort(bool ascending, bool nullsFirst)
            : ascending_(ascending), nullsFirst_(nullsFirst) {
        }

        void apply(
            const SelectivityVector &rows,
            std::vector<VectorPtr> &args,
            const TypePtr & /* outputType */,
            exec::EvalCtx &context,
            VectorPtr &result) const override;

    private:
        VectorPtr applyFlat(
            const SelectivityVector &rows,
            const VectorPtr &arg,
            exec::EvalCtx &context) const;

        const bool ascending_;
        const bool nullsFirst_;
    };

    std::shared_ptr<exec::VectorFunction> makeArraySort(
        const std::string &name,
        const std::vector<exec::VectorFunctionArg> &inputArgs,
        const core::QueryConfig &config);

    std::vector<std::shared_ptr<exec::FunctionSignature> > arraySortSignatures();

    std::shared_ptr<exec::VectorFunction> makeSortArray(
        const std::string &name,
        const std::vector<exec::VectorFunctionArg> &inputArgs,
        const core::QueryConfig &config);

    std::vector<std::shared_ptr<exec::FunctionSignature> > sortArraySignatures();
} // namespace kumo::pollux::functions::sparksql
